package cn.kgc.jdbc.util;

import com.mysql.jdbc.Driver;

import javax.sql.DataSource;
import java.sql.*;
import java.util.ResourceBundle;

/**
 * @author: mosin
 * @version: v1.0  2022/8/25
 * jdbc操作的工具类   快速的获取连接 和释放资源
 */
public class JDBCUtil {

    private JDBCUtil(){}

    private static String username;
    private static String driverClassName;
    private static String password;
    private static String url;

    static {  //  执行一次 类加载时

        ResourceBundle file = ResourceBundle.getBundle("jdbc");
        driverClassName = file.getString("driverClassName");
        url = file.getString("url");
        username = file.getString("username");
        password = file.getString("password");


    }


    //获取数据库连接的方法
    public  static Connection  getConnection(){
        //通过反射注册驱动
        Connection connection = null;
        try {
            Class.forName(driverClassName);
            connection = DriverManager.getConnection(url, username, password);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return connection;
    }

    //释放资源
    public static  void  closeAll(Connection connection, Statement statement, ResultSet resultSet){

        if(resultSet!=null){
            try {
                resultSet.close();
            } catch (SQLException throwables) {
                throwables.printStackTrace();
            }

        }

        if(statement!=null){

            try {
                statement.close();
            } catch (SQLException throwables) {
                throwables.printStackTrace();
            }

        }

        if(connection!=null){

            try {
                connection.close();
            } catch (SQLException throwables) {
                throwables.printStackTrace();
            }

        }

    }

}
